<template>
    <div class="wrapper">
        <div v-if="isAndroid" class="status-bar" :style="{'height': statusHeight}"></div>
        <bui-header title="首页"  @leftClick="menuShow" backgroundColor="#f49428">
        </bui-header>
        <text class="menuIcon" @click="menuShow">&#xe790;</text>
        <div style="margin-left:20;margin-right:20">
            <div class="titleDiv">
                <text class="title1">个人今日维保单概况</text>
                <switch class="switch" checked="true" @change="switchChart"></switch>
            </div>
            <div v-if="showChart" class="chart">
                <div class="chartLeft">
                    <bmchart style="width:500;height:400" :options="$format(pieData)" @finish='finish'></bmchart>
                </div>
                
                <div class="chartRight">
                    <div class="home-pie">
                        <text class="home-pie-text">我的保单量</text>
                        <text class="home-pie-number">{{allComplete}}</text>
                    </div>
                    <div class="home-pie">
                        <text class="home-pie-text">小组保单量</text>
                        <text class="home-pie-number">{{allTeamComplete}}</text>
                    </div>
                </div>
            </div>
            <text class="title">待接收和进行中维保单</text>
            <bui-tabbar :tabItems="tabTitles" 
                showSelectedLine=true 
                @change="onItemChange" 
                v-model="currentTab"
                background="#e0e0e0"
                selectedBackground="#2590f5"
                normalColor="#666666"
                selectedColor="#ffffff"
                borderBottomColor="#2590f5"
                titleSize="30px"></bui-tabbar>
            <slider class="slider" @change="onSliderChange" :index="currentTab">
                <scroller class="container" :style="scrollerStyle" alwaysScrollableVertical="true">
                    <refresh class="refresh" @refresh="onrefresh(4)" @pullingdown="onpullingdown" :display="refreshing ? 'show' : 'hide'">
                        <loading-indicator class="indicator"></loading-indicator>
                    </refresh>
                    <div class="list" :style="refreshStyle">
                        <div v-for="(item,index) in formItem0.content" :key="index">
                            <wxc-cell title="电梯工号" @wxcCellClicked="gotoDetail(item)">
                            <image class="image" slot="label" src="bmlocal://assets/liftId.png"></image>
                            <text :style="valueStyle">{{item.lNumber}}</text>
                            </wxc-cell>
                            <wxc-cell :has-margin="true" :has-bottom-border="false" title="维保日期">
                            <image class="image" slot="label" src="bmlocal://assets/calendar.png"></image>
                            <text :style="valueStyle">{{item.upkeepDate}}</text>
                            </wxc-cell>
                        </div>
                    </div>
                </scroller>
                <scroller class="container" :style="scrollerStyle" alwaysScrollableVertical="true">
                    <refresh class="refresh" @refresh="onrefresh(1)" @pullingdown="onpullingdown" :display="refreshing ? 'show' : 'hide'">
                        <loading-indicator class="indicator"></loading-indicator>
                    </refresh>
                    <div class="list" :style="refreshStyle">
                        <div v-for="(item,index) in formItem1.content" :key="index">
                            <wxc-cell title="电梯工号"  @wxcCellClicked="gotoDetail(item)">
                            <image class="image" slot="label" src="bmlocal://assets/liftId.png"></image>
                            <text :style="valueStyle">{{item.lNumber}}</text>
                            </wxc-cell>
                            <wxc-cell :has-margin="true" :has-bottom-border="false" title="维保日期">
                            <image class="image" slot="label" src="bmlocal://assets/calendar.png"></image>
                            <text :style="valueStyle">{{item.upkeepDate}}</text>
                            </wxc-cell>
                        </div>
                    </div>
                </scroller>
            </slider>
        </div>
        <wxc-loading :show="showLoading" :need-mask="mask"></wxc-loading>
        <menu :showMenu="showMenu" @closeMenu="menuClose"></menu>
    </div>
</template>
<script>
import menu from '../common/menu'
import util from '../utils/util';
import {buiHeader,buiIcon,buiTabbar} from 'bui-weex'
import { WxcTabPage, Utils,WxcCell,WxcButton,WxcLoading} from 'weex-ui';
var amap = weex.requireModule('amap')
var axios = weex.requireModule('bmAxios')
export default {
    components: {
        buiHeader,
        buiIcon,
        WxcTabPage,
        Utils,
        WxcCell,
        WxcButton,
        WxcLoading,
        menu,
        buiTabbar
    },
    created() {
        
    },
    data() {
        return {
            token:'',
            curHomeBackTriggerTimes:1,
            maxHomeBackTriggerTimes:2,
            isAndroid:false,
            tabTitles: [
                {
                title: '待接收',
                },
                {
                title: '进行中',
                }
            ],
            currentTab: 0,
            tabStyles: {
                bgColor: '#e0e0e0',
                titleColor: '#666666',
                activeTitleColor: '#fff',
                activeBgColor: '#2590f5',
                isActiveTitleBold: true,
                // iconWidth: 70,
                // iconHeight: 70,
                width: 355,
                height: 100,
                fontSize: 30,
                hasActiveBottom: true,
                // textPaddingLeft: 10,
                // textPaddingRight: 10,
                // normalBottomColor: 'rgba(0,0,0,0.4)',
                // normalBottomHeight: 1,
                hasRightIcon: true,
            },
            valueStyle:{
                color:'#999999',
                marginRight:40
            },
            formItem0: {},
            formItem1: {},
            formItem0Count: '',
            formItem1Count: '',
            allComplete: 0,
            allTeamComplete: 0,
            tabPageHeight: 1334,
            showLoading:false,
            mask:true,
            showMenu:false,
            refreshing: false,
            showChart:true,
            leftItem: {
                icon: '&#xe61a;',
            },
            statusHeight: Number.parseInt(this.statusBarHeight || weex.config.env.statusBarHeight || 40),
            containerHeight:'',
            pieData: {
                tooltip: {
                    show: true
                },
                legend: {
                orient: 'vertical',
                right: '1%',
                top: '30%',
                data: ['进行中', '已完成', '已分配']
                },
                series: [
                    {
                        // name: '访问来源',
                        type: 'pie',
                        hoverAnimation: false,
                        radius: ['30%', '80%'],
                        center: ['35%', '50%'],
                        // avoidLabelOverlap: false,
                        label: {
                        normal: {
                            show: true,
                            color: '#fff',
                            position: 'inner',
                            formatter: (obj) => {
                            return obj.value === 0 ? ' ' : obj.value
                            },
                            fontWeight: 'bolder',
                            fontSize: 14
                        }
                        // emphasis: {
                        //   show: true,
                        //   textStyle: {
                        //     fontSize: '30',
                        //     fontWeight: 'bold'
                        //   }
                        // }
                        },
                        itemStyle: {
                        normal: {
                            // 每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                            color: function (params) {
                            var colorList = ['rgb(244, 148, 40)', 'rgb(14, 202, 147)', 'rgb(239, 88, 73)']
                            return colorList[params.dataIndex]
                            }
                        }
                        },
                        data: [
                            // {value: 125, name: '进行中'},
                            // {value: 310, name: '已完成'},
                            // {value: 5, name: '已分配'}
                        ]
                    }
                ]
            },

        }
    },
    methods: {
        menuShow(){
          this.showMenu = true
        },
        menuClose(){
          this.showMenu = false
        },
        onrefresh(status){
            this.refreshing = true
            this.getUpkeepList(status)
        },
        switchChart(){
            this.showChart = !this.showChart
            if(this.showChart){
                this.scrollerStyle ={ height: this.containerHeight + 'px' }
            }else{
               if(this.isAndroid){
                    this.scrollerStyle ={ height: this.containerHeight+200 + 'px' }
                }else{
                    this.scrollerStyle ={ height: this.containerHeight+400 + 'px' }
                }
            }
        },
        onSliderChange(e){
            var index = e.index;
            this.currentTab=index;
        },
        getUpkeepList(status){
            let filter={}
            filter.page = 1
            filter.pageSize = 999
            filter.status = status
            this.showLoading = true
            this.$fetch({
                header:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer `+ this.token
                },
                method: 'POST',    
                name: 'myUpkeepList',
                data: filter
            }).then(resData => {
                if(resData.success){
                    //查询待接收
                    if(status == 4){
                        this.formItem0 = resData.data
                        this.tabTitles[0].title = '待接收'+ this.formItem0.totalElements+'单'
                        this.$storage.set('myUpkeepList0', JSON.stringify(resData.data))
                    }
                    //查询进行中
                    if(status == 1){
                        this.formItem1 = resData.data
                        this.tabTitles[1].title = '进行中'+ this.formItem1.totalElements+'单'
                        this.$storage.set('myUpkeepList1', JSON.stringify(resData.data))
                    }
                }else{
                    this.$notice.toast({
                        message: '网络错误'
                    })
                }
                
            }, error => {
                this.$notice.toast({
                    message: '网络错误'
                })
            })
            this.showLoading = false
            setTimeout(() => {
                this.refreshing = false
            }, 500)
        },
        retrievePersonalTodayOverView(){
            let filter={}
            this.$fetch({
                header:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer `+ this.token
                },
                method: 'POST',    
                name: 'todayUpkeepOverview',
                data: filter
            }).then(res => {
                if(res.success){
                    this.allComplete = res.data ? res.data.allComplete : 0
                    this.allTeamComplete = res.data ? res.data.allTeamComplete : 0
                    this.pieData.series[0].data = res.data ? [
                        {name: '进行中', value: res.data.upkeepCount.processingCount},
                        {name: '已完成', value: res.data.upkeepCount.completedCount},
                        {name: '已分配', value: res.data.upkeepCount.distributeCount}
                    ] : []
                }else{
                    this.$notice.toast({
                        message: '网络错误'
                    })
                }
               
            }, error => {
                this.$notice.toast({
                    message: '网络错误'
                })
            })
        },
        //保单详情页
        gotoDetail(item){
            this.showLoading = true
            let filter = {}
            filter.upkeepId = item.id
            this.$fetch({
                header:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer `+ this.token
                },
                method: 'POST',    
                name: 'getUpkeepDetail',
                data: filter
            }).then(resData => {
                if(resData.success){
                    this.$storage.set('upkeepDetail_'+item.id, JSON.stringify(resData.data))
                    this.showLoading = false
                    //跳转详情页
                    this.$router.open({
                        name: 'maintenaceDetail',
                        params:{upkeepId:item.id}
                    })
                }else{
                    this.$notice.toast({
                        message: '网络错误'
                    })
                }
                
            }, error => {
                this.$notice.toast({
                    message: '网络错误'
                })
            })
            
            this.showLoading = false
        },
        // getAddress(locationLng,locationLat){
        //     // 示例
        //     let data = {}
        //     let _this = this
        //     let loc = locationLng+','+locationLat
        //     data.location = loc
        //     data.key = 'c1f73016285c30b57fda31598f5757c2'
        //     this.$fetch({
        //         method: 'GET',
        //         url: 'https://restapi.amap.com/v3/geocode/regeo',
        //         header: {},
        //         data: data,
        //         timeout: 3000
        //     }, function(resData){
        //         if(!resData){
        //             _this.$notice.toast({
        //                 message: '定位失败'
        //             })
        //             return
        //         }else{
        //            _this.$storage.set('address',resData.data.regeocode.formatted_address)
        //         }
        //     })
        // },
        getAddress(locationLng,locationLat){
            let data = {}
            let _this = this
            let loc = locationLng+','+locationLat
            data.location = loc
            data.key = 'c1f73016285c30b57fda31598f5757c2'
            this.$fetch({
                method: 'GET',
                url: 'https://restapi.amap.com/v3/geocode/regeo',
                header: {},
                data: data,
                timeout: 3000
            }).then(resData => {
                if(resData.status == "1"){
                    this.$storage.set('address',resData.regeocode.formatted_address)
                }else{
                    this.$notice.toast({
                        message: '定位失败'
                    })
                }
            }, error => {
                this.$notice.toast({
                    message: '定位失败'
                })
            })
        },
        saveLocation(locationLng,locationLat){
            let filter = {}
            filter.locationX = locationLng
            filter.locationY = locationLat
            this.$fetch({
                header:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer `+ this.token
                },
                method: 'POST',    
                name: 'saveLocation',
                data: filter
            }).then(resData => {
                if(resData.success){
                    // this.$notice.toast({
                    //     message: '上传成功'
                    // })
                }else{
                    this.$notice.toast({
                        message: '网络错误'
                    })
                }
            }, error => {
                this.$notice.toast({
                    message: '网络错误'
                })
            })
        },
        androidFinishApp() {
            const globalEvent = weex.requireModule("globalEvent");
            globalEvent.addEventListener("homeBack", options => {
                this.curHomeBackTriggerTimes === this.maxHomeBackTriggerTimes &&
                this.$router.finish();

                this.$notice.toast({
                    message: '再次点击退出'
                });
                this.curHomeBackTriggerTimes++;
                setTimeout(() => {
                    this.curHomeBackTriggerTimes = 1
                }, 1000)
            });
            
        }
    },
    created(){
        // util.initIconFont()
        this.androidFinishApp()
        this.$notice.loading.show()
        this.isAndroid = Utils.env.isAndroid()
        if(Utils.env.isAndroid()){
            this.refreshStyle = {marginTop:'-100px'}
        }
        const tabPageHeight = Utils.env.getPageHeight()
        if(Utils.env.isIOS()){
            this.containerHeight = tabPageHeight-this.tabStyles.height-135-550
        }else{
            this.containerHeight = tabPageHeight-this.tabStyles.height-400-90-110-260
        }
        this.scrollerStyle = { height: this.containerHeight + 'px' }

        // 获取token
        this.token = this.$storage.getSync('token')
        if(!this.token){
            this.$router.setHomePage('/pages/login.js')
        }
        //定位
        amap.initAmap('e6a87676260d70740d8303b686dfd056')
        this.$geo.get().then(data => {
            //获取行政位置
            // var locationLng = '120.246842'
            // var locationLat = '31.546071'
            this.saveLocation(data.locationLng,data.locationLat)
            this.getAddress(data.locationLng,data.locationLat)
        }, error => {
            this.$notice.toast({
                message: '定位失败'
            })
        })
        // if(Utils.env.isAndroid()){
        //     var id = 'test'
        //     let _this = this
        //     amap.getUserLocation("test",function (resData) {
        //         if(resData.result == 'success'){
        //             _this.$storage.set('address',resData.data.position[2])
        //             _this.saveLocation(resData.data.position[0],resData.data.position[1])
        //         }else{
        //             _this.$notice.toast({
        //                 message: '定位失败'
        //             })
        //         }
        //     });  
        // }else{
        //     this.$geo.get().then(data => {
        //         //获取行政位置
        //         // var locationLng = '120.246842'
        //         // var locationLat = '31.546071'
        //         this.saveLocation(data.locationLng,data.locationLat)
        //         this.getAddress(data.locationLng,data.locationLat)
        //     }, error => {
        //         this.$notice.toast({
        //             message: '定位失败'
        //         })
        //     })
        // }

        // 获取缓存数据
        this.$storage.get('myUpkeepList0').then(resData => {
            this.formItem0 = JSON.parse(resData);
            this.tabTitles[0].title = '待接收'+ this.formItem0.totalElements+'单'
        },error => {
            this.getUpkeepList(4)
        })

        this.$storage.get('myUpkeepList1').then(resData => {
            this.formItem1 = JSON.parse(resData);
            this.tabTitles[1].title = '进行中'+ this.formItem1.totalElements+'单'
        },error => {
            this.getUpkeepList(1)
        })

        //获取统计数据
        this.retrievePersonalTodayOverView();
        this.$notice.loading.hide()
    },
    
}
</script>
<style scoped>
.status-bar{
    background-color:#f49428;
}
.image {
    width: 50px;
    height: 50px;
    margin-right: 20px;
}
.container {
    width: 750px;
    background-color: #f2f3f4;
}
.refresh {
    width: 750px;
    height: 100px;
    display: -ms-flex;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}
.indicator {
    height: 80px;
    width: 80px;
    color: #f49428;
}
.chart{
    background-color: #ffffff;
    flex-direction: row;
}
.chartLeft{
    flex:7;
    height: 400px;
}
.chartRight{
    flex:3;
    height: 400px;
    border-left-width: 1;
    border-color: #e2e2e2;
    flex-direction:column;
}
.home-pie{
    flex: 1
}
.home-pie-text{
  text-align: center; 
  color:#90908D;
  font-size:30px;
  margin-top: 50px;
}
.home-pie-number{
  text-align: center;
  font-size:50px;
  font-weight: bold;
}
.title{
    color: #999999;
    margin: 10 0 10 10;
    font-size: 25;
}
.titleDiv{
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
}
.title1{
    flex: 6;
    color: #999999;
    margin: 10 0 10 10;
    font-size: 25;
}
.switch{
    flex: 1;
    margin: 10 0 10 10;
}
.menuIcon{
    font-family: iconfont;
    color: #ffffff;
    font-size: 50px;
    position: absolute;
    top: 65;
    left: 20;
}
</style>

